package com.tsx.aspect;

import com.tsx.annotation.SpElRecord;
import com.tsx.utils.SpELParserUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;

@Aspect
@Component
public class SpELAspect {
    @Pointcut("@annotation(com.tsx.annotation.SpElRecord)")
    public void pointcut() {
    }

    @AfterReturning(pointcut = "pointcut()")
    public void doAfter(JoinPoint joinPoint) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        Object[] args = joinPoint.getArgs();
        String[] parameterNames = methodSignature.getParameterNames();
        SpElRecord spElRecord = method.getAnnotation(SpElRecord.class);
        String keyStr = spElRecord.key();
        if (StringUtils.hasText(keyStr)) {
            String key = SpELParserUtils.parse(args, parameterNames, keyStr, String.class);
            System.out.println("key = " + key);
        }
    }

    public static void main(String[] args) {
        String expressionStr = "1+1";
        ExpressionParser parser = new SpelExpressionParser();
        Expression expression = parser.parseExpression(expressionStr);
        Integer res = expression.getValue(Integer.class);
        System.out.println("res = " + res);
    }
}
